package com.bitrate.dagger.oss.client;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.bitrate.dagger.oss.properties.OssProperties;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * 阿里云OSS文件上传
 *
 */
@RequiredArgsConstructor
public class OssClient implements InitializingBean {

	protected static final Logger logger = LoggerFactory.getLogger(OssClient.class);

	private final OssProperties ossProperties;

	private OSS ossClient;

	/**
	 * @return 上传图片
	 */
	public String uploadImage(MultipartFile file, String fileName) {
		String uploadUrl = "";
		String bucketName = ossProperties.getBucketName();
		try {
			byte[] byteArr = file.getBytes();
			InputStream inputStream = new ByteArrayInputStream(byteArr);
			// 获取文件后缀名
			String fileType = StrUtil.subAfter(file.getOriginalFilename(), ".", true);
			fileName = fileName.concat(".").concat(fileType);
			// 添加 ContentType
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentType(file.getContentType());
			ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
			Date expire = DateUtil.offsetMonth(new Date(), 120);
			uploadUrl = ossClient.generatePresignedUrl(bucketName, fileName, expire).toString();
			uploadUrl = uploadUrl.substring(0, uploadUrl.indexOf("?"));
		} catch (Exception e) {
			logger.error("aliOssUpload Fail:" + e.getMessage());
			return uploadUrl;
		}
		return uploadUrl;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		String endpoint = ossProperties.getEndpoint();
		String accessKeyId = ossProperties.getAccessKeyId();
		String accessKeySecret = ossProperties.getAccessKeySecret();
		this.ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
	}
}
